home *** CD-ROM | disk | FTP | other *** search
/ Collection of Internet / Collection of Internet.iso / faq / news / perl_faq / part3 < prev    next >
Text File  |  1993-10-01  |  44KB  |  1,281 lines

  1. Newsgroups: comp.lang.perl,news.answers
  2. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!spool.mu.edu!uwm.edu!cs.utexas.edu!uunet!boulder!wraeththu.cs.colorado.edu!tchrist
  3. From: Tom Christiansen <tchrist@cs.Colorado.EDU>
  4. Subject: Perl Frequently Asked Questions, part 3 of 4
  5. Message-ID: <CE9Br9.275@Colorado.EDU>
  6. Followup-To: comp.lang.perl
  7. Originator: tchrist@wraeththu.cs.colorado.edu
  8. Sender: news@Colorado.EDU (USENET News System)
  9. Organization: University of Colorado at Boulder
  10. Date: Sat, 2 Oct 1993 06:37:56 GMT
  11. Approved: news-answers-request@MIT.Edu
  12. Expires: Wed, 1 Dec 1993 12:00:00 GMT
  13. Lines: 1265
  14. Xref: senator-bedfellow.mit.edu comp.lang.perl:20584 news.answers:13122
  15.  
  16. Archive-name: perl-faq/part3
  17. Version: $Id: perl-tech1,v 1.1 93/10/02 00:27:00 tchrist Exp Locker: tchrist $
  18.  
  19. This posting contains answers to the following technical questions
  20. regarding Perl:
  21.  
  22. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  23. 2.2) Why don't backticks work as they do in shells?  
  24. 2.3) How come Perl operators have different precedence than C operators?
  25. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  26. 2.5) How can I call my system's unique C functions from Perl?
  27. 2.6) Where do I get the include files to do ioctl() or syscall()?
  28. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  29. 2.8) How can I detect keyboard input without reading it, 
  30. 2.9) how can I read a single character from the keyboard under UNIX and DOS?
  31. 2.10) How can I make an array of arrays or other recursive data types?
  32. 2.11) How do I make an array of structures containing various data types?
  33. 2.12) How can I quote a variable to use in a regexp?
  34. 2.13) Why do setuid Perl scripts complain about kernel problems?
  35. 2.14) How do I open a pipe both to and from a command?
  36. 2.15) How can I change the first N letters of a string?
  37. 2.16) How can I manipulate fixed-record-length files?
  38. 2.17) How can I make a file handle local to a subroutine?
  39. 2.18) How can I extract just the unique elements of an array?
  40. 2.19) How can I call alarm() or usleep() from Perl?
  41. 2.20) How can I test whether an array contains a certain element?
  42. 2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  43. 2.22) Why doesn't Perl interpret my octal data octally?
  44. 2.23) How do I sort an associative array by value instead of by key?
  45. 2.24) How can I capture STDERR from an external command?
  46. 2.25) Why doesn't open return an error when a pipe open fails?
  47. 2.26) How can I compare two date strings?
  48. 2.27) What's the fastest way to code up a given task in perl?
  49. 2.28) How can I know how many entries are in an associative array?
  50.  
  51.  
  52. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  53.  
  54.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  55.     and % for hashed arrays.  The * means all types of that symbol name
  56.     and are sometimes used like pointers; the <> are used for inputting
  57.     a record from a filehandle.  See the question on arrays of arrays
  58.     for more about Perl pointers.
  59.  
  60.     Always make sure to use a $ for single values and @ for multiple ones.
  61.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  62.     which is a list of length one (not a scalar), and is a fairly common
  63.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  64.     not really doing what you think it's doing for the reason you think
  65.     it's doing it, which means one of these days, you'll shoot yourself
  66.     in the foot; ponder for a moment what these will really do:
  67.     @foo[0] = `cmd args`;
  68.     @foo[2] = <FILE>;
  69.     Just always say $foo[2] and you'll be happier.
  70.  
  71.     This may seem confusing, but try to think of it this way:  you use the
  72.     character of the type which you *want back*.  You could use @foo[1..3] for
  73.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  74.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  75.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  76.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  77.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  78.  
  79.     While there are a few places where you don't actually need these type
  80.     specifiers, except for files, you should always use them.  Note that
  81.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  82.     getline function, that is, it reads a line from the handle FILE.  When
  83.     doing open, close, and other operations besides the getline function on
  84.     files, do NOT use the brackets.
  85.  
  86.     Beware of saying:
  87.     $foo = BAR;
  88.     Which wil be interpreted as 
  89.     $foo = 'BAR';
  90.     and not as 
  91.     $foo = <BAR>;
  92.     If you always quote your strings, you'll avoid this trap.
  93.  
  94.     Normally, files are manipulated something like this (with appropriate
  95.     error checking added if it were production code):
  96.  
  97.     open (FILE, ">/tmp/foo.$$");
  98.     print FILE "string\n";
  99.     close FILE;
  100.  
  101.     If instead of a filehandle, you use a normal scalar variable with file
  102.     manipulation functions, this is considered an indirect reference to a
  103.     filehandle.  For example,
  104.  
  105.     $foo = "TEST01";
  106.     open($foo, "file");
  107.  
  108.     After the open, these two while loops are equivalent:
  109.  
  110.     while (<$foo>) {}
  111.     while (<TEST01>) {}
  112.  
  113.     as are these two statements:
  114.     
  115.     close $foo;
  116.     close TEST01;
  117.  
  118.     but NOT to this:
  119.  
  120.     while (<$TEST01>) {} # error
  121.         ^
  122.         ^ note spurious dollar sign
  123.  
  124.     This is another common novice mistake; often it's assumed that
  125.  
  126.     open($foo, "output.$$");
  127.  
  128.     will fill in the value of $foo, which was previously undefined.  
  129.     This just isn't so -- you must set $foo to be the name of a valid
  130.     filehandle before you attempt to open it.
  131.  
  132.  
  133. 2.2) Why don't backticks work as they do in shells?  
  134.  
  135.     Several reason.  One is because backticks do not interpolate within
  136.     double quotes in Perl as they do in shells.  
  137.     
  138.     Let's look at two common mistakes:
  139.  
  140.          $foo = "$bar is `wc $file`";  # WRONG
  141.  
  142.     This should have been:
  143.  
  144.      $foo = "$bar is " . `wc $file`;
  145.  
  146.     But you'll have an extra newline you might not expect.  This
  147.     does not work as expected:
  148.  
  149.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  150.  
  151.     Because backticks do not automatically eat trailing or embedded
  152.     newlines.  The chop() function will remove the last character from
  153.     a string.  This should have been:
  154.  
  155.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  156.  
  157.     You should also be aware that while in the shells, embedding
  158.     single quotes will protect variables, in Perl, you'll need 
  159.     to escape the dollar signs.
  160.  
  161.     Shell: foo=`cmd 'safe $dollar'`
  162.     Perl:  $foo=`cmd 'safe \$dollar'`;
  163.     
  164.  
  165. 2.3) How come Perl operators have different precedence than C operators?
  166.  
  167.     Actually, they don't; all C operators have the same precedence in Perl as
  168.     they do in C.  The problem is with a class of functions called list
  169.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  170.     bizarre in that they have different precedence depending on whether you
  171.     look on the left or right of them.  Basically, they gobble up all things
  172.     on their right.  For example,
  173.  
  174.     unlink $foo, "bar", @names, "others";
  175.  
  176.     will unlink all those file names.  A common mistake is to write:
  177.  
  178.     unlink "a_file" || die "snafu";
  179.  
  180.     The problem is that this gets interpreted as
  181.  
  182.     unlink("a_file" || die "snafu");
  183.  
  184.     To avoid this problem, you can always make them look like function calls
  185.     or use an extra level of parentheses:
  186.  
  187.     (unlink "a_file") || die "snafu";
  188.     unlink("a_file")  || die "snafu";
  189.  
  190.     Sometimes you actually do care about the return value:
  191.  
  192.     unless ($io_ok = print("some", "list")) { } 
  193.  
  194.     Yes, print() return I/O success.  That means
  195.  
  196.     $io_ok = print(2+4) * 5;
  197.  
  198.     returns 5 times whether printing (2+4) succeeded, and 
  199.     print(2+4) * 5;
  200.     returns the same 5*io_success value and tosses it.
  201.  
  202.     See the Perl man page's section on Precedence for more gory details,
  203.     and be sure to use the -w flag to catch things like this.
  204.  
  205.  
  206. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  207.  
  208.     The natural way to program in those languages may not make for the fastest
  209.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  210.     see the a2p man page for tweaks you can make.
  211.  
  212.     Two of Perl's strongest points are its associative arrays and its regular
  213.     expressions.  They can dramatically speed up your code when applied
  214.     properly.  Recasting your code to use them can help a lot.
  215.  
  216.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  217.     * operators can take a very long time to compute.  Don't use ()'s unless
  218.     you really need them.  Anchor your string to the front if you can.
  219.  
  220.     Something like this:
  221.     next unless /^.*%.*$/; 
  222.     runs more slowly than the equivalent:
  223.     next unless /%/;
  224.  
  225.     Note that this:
  226.     next if /Mon/;
  227.     next if /Tue/;
  228.     next if /Wed/;
  229.     next if /Thu/;
  230.     next if /Fri/;
  231.     runs faster than this:
  232.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  233.     which in turn runs faster than this:
  234.     next if /Mon|Tue|Wed|Thu|Fri/;
  235.     which runs *much* faster than:
  236.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  237.  
  238.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  239.  
  240.     Remember that a printf costs more than a simple print.
  241.  
  242.     Don't split() every line if you don't have to.
  243.  
  244.     Another thing to look at is your loops.  Are you iterating through 
  245.     indexed arrays rather than just putting everything into a hashed 
  246.     array?  For example,
  247.  
  248.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  249.  
  250.     for $i ($[ .. $#list) {
  251.         if ($pattern eq $list[$i]) { $found++; } 
  252.     } 
  253.  
  254.     First of all, it would be faster to use Perl's foreach mechanism
  255.     instead of using subscripts:
  256.  
  257.     foreach $elt (@list) {
  258.         if ($pattern eq $elt) { $found++; } 
  259.     } 
  260.  
  261.     Better yet, this could be sped up dramatically by placing the whole
  262.     thing in an associative array like this:
  263.  
  264.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  265.          'mno', 1, 'pqr', 1, 'stv', 1 );
  266.     $found += $list{$pattern};
  267.     
  268.     (but put the %list assignment outside of your input loop.)
  269.  
  270.     You should also look at variables in regular expressions, which is
  271.     expensive.  If the variable to be interpolated doesn't change over the
  272.     life of the process, use the /o modifier to tell Perl to compile the
  273.     regexp only once, like this:
  274.  
  275.     for $i (1..100) {
  276.         if (/$foo/o) {
  277.         &some_func($i);
  278.         } 
  279.     } 
  280.  
  281.     Finally, if you have a bunch of patterns in a list that you'd like to 
  282.     compare against, instead of doing this:
  283.  
  284.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  285.     foreach $pat (@pats) {
  286.         if ( $name =~ /^$pat$/ ) {
  287.         &some_func();
  288.         last;
  289.         }
  290.     }
  291.  
  292.     If you build your code and then eval it, it will be much faster.
  293.     For example:
  294.  
  295.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  296.     $code = <<EOS
  297.         while (<>) { 
  298.             study;
  299. EOS
  300.     foreach $pat (@pats) {
  301.         $code .= <<EOS
  302.         if ( /^$pat\$/ ) {
  303.             &some_func();
  304.             next;
  305.         }
  306. EOS
  307.     }
  308.     $code .= "}\n";
  309.     print $code if $debugging;
  310.     eval $code;
  311.  
  312.  
  313.  
  314. 2.5) How can I call my system's unique C functions from Perl?
  315.  
  316.     If these are system calls and you have the syscall() function, then
  317.     you're probably in luck -- see the next question.  For arbitrary
  318.     library functions, it's not quite so straight-forward.  While you
  319.     can't have a C main and link in Perl routines, if you're
  320.     determined, you can extend Perl by linking in your own C routines.
  321.     See the usub/ subdirectory in the Perl distribution kit for an example
  322.     of doing this to build a Perl that understands curses functions.  It's
  323.     neither particularly easy nor overly-documented, but it is feasible.
  324.  
  325.  
  326. 2.6) Where do I get the include files to do ioctl() or syscall()?
  327.  
  328.     These are generated from your system's C include files using the h2ph
  329.     script (once called makelib) from the Perl source directory.  This will
  330.     make files containing subroutine definitions, like &SYS_getitimer, which
  331.     you can use as arguments to your function.
  332.  
  333.     You might also look at the h2pl subdirectory in the Perl source for how to
  334.     convert these to forms like $SYS_getitimer; there are both advantages and
  335.     disadvantages to this.  Read the notes in that directory for details.  
  336.    
  337.     In both cases, you may well have to fiddle with it to make these work; it
  338.     depends how funny-looking your system's C include files happen to be.
  339.  
  340.     If you're trying to get at C structures, then you should take a look
  341.     at using c2ph, which uses debugger "stab" entries generated by your
  342.     BSD or GNU C compiler to produce machine-independent perl definitions
  343.     for the data structures.  This allows to you avoid hardcoding
  344.     structure layouts, types, padding, or sizes, greatly enhancing
  345.     portability.  c2ph comes with the perl distribution.  On an SCO
  346.     system, GCC only has COFF debugging support by default, so you'll have
  347.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  348.     get c2ph to work there.
  349.  
  350.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  351.     for more traps and tips on this process.
  352.  
  353.  
  354. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  355.  
  356.     Well, it does.  The thing to remember is that local() provides an array
  357.     context, and that the <FILE> syntax in an array context will read all the
  358.     lines in a file.  To work around this, use:
  359.  
  360.     local($foo);
  361.     $foo = <FILE>;
  362.  
  363.     You can use the scalar() operator to cast the expression into a scalar
  364.     context:
  365.  
  366.     local($foo) = scalar(<FILE>);
  367.  
  368.  
  369. 2.8) How can I detect keyboard input without reading it? 
  370.  
  371.     You should check out the Frequently Asked Questions list in
  372.     comp.unix.* for things like this: the answer is essentially the same.
  373.     It's very system dependent.  Here's one solution that works on BSD
  374.     systems:
  375.  
  376.     sub key_ready {
  377.         local($rin, $nfd);
  378.         vec($rin, fileno(STDIN), 1) = 1;
  379.         return $nfd = select($rin,undef,undef,0);
  380.     }
  381.  
  382.  
  383. 2.9) How can I read a single character from the keyboard under UNIX and DOS?
  384.  
  385.     A closely related question to the no-echo question is how to input a
  386.     single character from the keyboard.  Again, this is a system dependent
  387.     operation.  The following code that may or may not help you.  It should
  388.     work on both SysV and BSD flavors of UNIX:
  389.  
  390.     $BSD = -f '/vmunix';
  391.     if ($BSD) {
  392.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  393.     }
  394.     else {
  395.         system "stty", '-icanon',
  396.         system "stty", 'eol', "\001"; 
  397.     }
  398.  
  399.     $key = getc(STDIN);
  400.  
  401.     if ($BSD) {
  402.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  403.     }
  404.     else {
  405.         system "stty", 'icanon';
  406.         system "stty", 'eol', '^@'; # ascii null
  407.     }
  408.     print "\n";
  409.  
  410.     You could also handle the stty operations yourself for speed if you're
  411.     going to be doing a lot of them.  This code works to toggle cbreak
  412.     and echo modes on a BSD system:
  413.  
  414.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  415.     local($on) = $_[0];
  416.     local($sgttyb,@ary);
  417.     require 'sys/ioctl.ph';
  418.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  419.  
  420.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  421.  
  422.     @ary = unpack($sgttyb_t,$sgttyb);
  423.     if ($on) {
  424.         $ary[4] |= &CBREAK;
  425.         $ary[4] &= ~&ECHO;
  426.     } else {
  427.         $ary[4] &= ~&CBREAK;
  428.         $ary[4] |= &ECHO;
  429.     }
  430.     $sgttyb = pack($sgttyb_t,@ary);
  431.  
  432.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  433.     }
  434.  
  435.     Note that this is one of the few times you actually want to use the
  436.     getc() function; it's in general way too expensive to call for normal
  437.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  438.     or sysread() functions.
  439.  
  440.     For perspectives on more portable solutions, use anon ftp to retrieve
  441.     the file /pub/perl/info/keypress from convex.com.
  442.  
  443.     For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports:
  444.  
  445.     To put the PC in "raw" mode, use ioctl with some magic numbers gleaned
  446.     from msdos.c (Perl source file) and Ralf Brown's interrupt list (comes
  447.     across the net every so often):
  448.  
  449.     $old_ioctl = ioctl(STDIN,0,0);     # Gets device info
  450.     $old_ioctl &= 0xff;
  451.     ioctl(STDIN,1,$old_ioctl | 32);    # Writes it back, setting bit 5
  452.  
  453.     Then to read a single character:
  454.  
  455.     sysread(STDIN,$c,1);               # Read a single character
  456.  
  457.     And to put the PC back to "cooked" mode:
  458.  
  459.     ioctl(STDIN,1,$old_ioctl);         # Sets it back to cooked mode.
  460.  
  461.  
  462.     So now you have $c.  If ord($c) == 0, you have a two byte code, which
  463.     means you hit a special key.  Read another byte (sysread(STDIN,$c,1)),
  464.     and that value tells you what combination it was according to this
  465.     table:
  466.  
  467.     # PC 2-byte keycodes = ^@ + the following:
  468.  
  469.     # HEX     KEYS
  470.     # ---     ----
  471.     # 0F      SHF TAB
  472.     # 10-19   ALT QWERTYUIOP
  473.     # 1E-26   ALT ASDFGHJKL
  474.     # 2C-32   ALT ZXCVBNM
  475.     # 3B-44   F1-F10
  476.     # 47-49   HOME,UP,PgUp
  477.     # 4B      LEFT
  478.     # 4D      RIGHT
  479.     # 4F-53   END,DOWN,PgDn,Ins,Del
  480.     # 54-5D   SHF F1-F10
  481.     # 5E-67   CTR F1-F10
  482.     # 68-71   ALT F1-F10
  483.     # 73-77   CTR LEFT,RIGHT,END,PgDn,HOME
  484.     # 78-83   ALT 1234567890-=
  485.     # 84      CTR PgUp
  486.  
  487.     This is all trial and error I did a long time ago, I hope I'm reading the
  488.     file that worked.
  489.  
  490.  
  491. 2.10) How can I make an array of arrays or other recursive data types?
  492.  
  493.     Remember that Perl isn't about nested data structures (actually,
  494.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  495.     somewhat).  It's about flat ones, so if you're trying to do this, you
  496.     may be going about it the wrong way or using the wrong tools.  You
  497.     might try parallel arrays with common subscripts.
  498.  
  499.     But if you're bound and determined, you can use the multi-dimensional
  500.     array emulation of $a{'x','y','z'}, or you can make an array of names
  501.     of arrays and eval it.
  502.  
  503.     For example, if @name contains a list of names of arrays, you can 
  504.     get at a the j-th element of the i-th array like so:
  505.  
  506.     $ary = $name[$i];
  507.     $val = eval "\$$ary[$j]";
  508.  
  509.     or in one line
  510.  
  511.     $val = eval "\$$name[$i][\$j]";
  512.  
  513.     You could also use the type-globbing syntax to make an array of *name
  514.     values, which will be more efficient than eval.  Here @name hold
  515.     a list of pointers, which we'll have to dereference through a temporary
  516.     variable.
  517.  
  518.     For example:
  519.  
  520.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  521.  
  522.     In fact, you can use this method to make arbitrarily nested data
  523.     structures.  You really have to want to do this kind of thing
  524.     badly to go this far, however, as it is notationally cumbersome.
  525.  
  526.     Let's assume you just simply *have* to have an array of arrays of
  527.     arrays.  What you do is make an array of pointers to arrays of
  528.     pointers, where pointers are *name values described above.  You
  529.     initialize the outermost array normally, and then you build up your
  530.     pointers from there.  For example:
  531.  
  532.     @w = ( 'ww' .. 'xx' );
  533.     @x = ( 'xx' .. 'yy' );
  534.     @y = ( 'yy' .. 'zz' );
  535.     @z = ( 'zz' .. 'zzz' );
  536.  
  537.     @ww = reverse @w;
  538.     @xx = reverse @x;
  539.     @yy = reverse @y;
  540.     @zz = reverse @z;
  541.  
  542.     Now make a couple of array of pointers to these:
  543.  
  544.     @A = ( *w, *x, *y, *z );
  545.     @B = ( *ww, *xx, *yy, *zz );
  546.  
  547.     And finally make an array of pointers to these arrays:
  548.  
  549.     @AAA = ( *A, *B );
  550.  
  551.     To access an element, such as AAA[i][j][k], you must do this:
  552.  
  553.     local(*foo) = $AAA[$i];
  554.     local(*bar) = $foo[$j];
  555.     $answer = $bar[$k];
  556.  
  557.     Similar manipulations on associative arrays are also feasible.
  558.  
  559.     You could take a look at recurse.pl package posted by Felix Lee
  560.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  561.     associative arrays) by using type glob references and some pretty serious
  562.     wizardry.
  563.  
  564.     In C, you're used to creating recursive datatypes for operations
  565.     like recursive decent parsing or tree traversal.  In Perl, these
  566.     algorithms are best implemented using associative arrays.  Take an
  567.     array called %parent, and build up pointers such that $parent{$person}
  568.     is the name of that person's parent.  Make sure you remember that
  569.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  570.     be used to implement general graph traversal algorithms as well.
  571.  
  572.     In Perl5, it's quite easy to declare these things.  For example
  573.  
  574.     @A = (
  575.         [ 'ww' .. 'xx'  ], 
  576.         [ 'xx' .. 'yy'  ], 
  577.         [ 'yy' .. 'zz'  ], 
  578.         [ 'zz' .. 'zzz' ], 
  579.     );
  580.  
  581.     And now reference $A[2]->[0] to pull out "yy".  These may also nest
  582.     and mix with tables:
  583.  
  584.     %T = (
  585.         key0, { k0, v0, k1, v1 },    
  586.         key1, { k2, v2, k3, v3 },    
  587.         key2, { k2, v2, k3, [ 0, 'a' .. 'z' ] },    
  588.     );
  589.     
  590.     Allosing you to reference $T{key2}->{k3}->[3] to pull out 'c'.
  591.  
  592.  
  593.  
  594. 2.11) How do I make an array of structures containing various data types?
  595.  
  596.     Well, soon you may not have to, but for now, let's look at ways to 
  597.     synthesize these.
  598.  
  599.     One scheme I've invented uses what I call pseudoanonymous packages.
  600.     This was motivated because I wanted an associative array of structures
  601.     in which each structure contained not merely scalar data, but also lists
  602.     and tables.   
  603.  
  604.     The table (read: associative array) is called %Active_Folders, whose
  605.     key is the name of the folder, and whose values are, well, *logically*
  606.     they're each a structure whose components look like this:
  607.  
  608.     $Current_Folder
  609.     $Current_Seq  
  610.     $Current_Line
  611.     $Top_Line   
  612.     $Incomplete_Read    
  613.     $Folder_ID  
  614.     $Last_Typed 
  615.     @Scan_Lines
  616.     %Scan_IDs 
  617.     %Deleted 
  618.  
  619.     The way it works is that I only have one folder active at once.
  620.     Those symbols as listed above are accessible from anywhere in the
  621.     program.  The trick is that when I want to switch folders, I change
  622.     what they point to!  You see, there's a package for each folder name
  623.     that contains the real data.  So, it's not like I get to dereference
  624.  
  625.     $Active_Folder{$foldername}->$Current_Line
  626.  
  627.     or 
  628.     $Active_Folder{$foldername}->$Scan_IDs{$msgnum}
  629.  
  630.     Although I'd like to.  I have to switch folders to $foldername first,
  631.     and then access the individual fields directly.  The package isn't intuitable,
  632.     which is why it's a pseudoanonymous one.
  633.  
  634.     Hm, I've this scary feeling that in Perl5, the last line will really read:
  635.  
  636.     ${$Active_Folder{$foldername}->Scan_IDs}->{$msgnum}
  637.  
  638.     or something, which is truly impossible for my brain to parse.  But I'm not
  639.     real clear on it.  I get muddled up part way through whenever Larry explains
  640.     how multiple levels of deferencing will work, and I'm not even sure I'll be
  641.     able to get away with the above without setting up lots of pointers first.
  642.  
  643.     Anyway, here's the code that allows associative arrays of structures of 
  644.     random data types.  I haven't done more than one level yet, although 
  645.     surely you could embed the value of $Active_Folders{$folder} as a $Prev_Folder
  646.     field in each, then do the right appropriate thing.
  647.  
  648.     sub gensym { 'gensym_' . ++$gensym'symbol } 
  649.  
  650.     sub activate_folder {
  651.         local($folder) = @_;
  652.  
  653.         &assert('$folder',$folder);
  654.  
  655.         $Last_Seq = $Current_Seq;
  656.  
  657.         if (! defined $Active_Folders{$folder}) {
  658.         $Active_Folders{$folder} = &gensym;
  659.         push(@Active_Folders, $folder);
  660.         }
  661.  
  662.         local($package) = $Active_Folders{$folder};
  663.  
  664.         local($code)=<<"EOF";
  665.         {
  666.             package $package;
  667.             *'Current_Folder    = *Current_Folder;
  668.             *'Current_Seq       = *Current_Seq;
  669.             *'Current_Line      = *Current_Line;
  670.             *'Top_Line          = *Top_Line;
  671.             *'Scan_Lines        = *Scan_Lines;
  672.             *'Scan_IDs          = *Scan_IDs;
  673.             *'Incomplete_Read   = *Incomplete_Read;
  674.             *'Folder_ID         = *Folder_ID;
  675.             *'Last_Typed        = *Last_Typed;
  676.             *'Deleted           = *Deleted;
  677.             }
  678.         EOF
  679.         eval $code;
  680.         $Current_Seq = $folder;
  681.  
  682.         &panic("bad eval: $@\n$code\n") if $@;
  683.     } 
  684.  
  685.  
  686. 2.12) How can I quote a variable to use in a regexp?
  687.  
  688.     From the manual:
  689.  
  690.     $pattern =~ s/(\W)/\\$1/g;
  691.  
  692.     Now you can freely use /$pattern/ without fear of any unexpected
  693.     meta-characters in it throwing off the search.  If you don't know
  694.     whether a pattern is valid or not, enclose it in an eval to avoid
  695.     a fatal run-time error.
  696.  
  697.  
  698. 2.13) Why do setuid Perl scripts complain about kernel problems?
  699.  
  700.     This message:
  701.  
  702.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  703.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  704.  
  705.     is triggered because setuid scripts are inherently insecure due to a
  706.     kernel bug.  If your system has fixed this bug, you can compile Perl
  707.     so that it knows this.  Otherwise, create a setuid C program that just
  708.     execs Perl with the full name of the script.  Larry's wrapsuid 
  709.     script can help.
  710.  
  711.  
  712. 2.14) How do I open a pipe both to and from a command?
  713.  
  714.     In general, this is a dangerous move because you can find yourself in a
  715.     deadlock situation.  It's better to put one end of the pipe to a file.
  716.     For example:
  717.  
  718.     # first write some_cmd's input into a_file, then 
  719.     open(CMD, "some_cmd its_args < a_file |");
  720.     while (<CMD>) {
  721.  
  722.     # or else the other way; run the cmd
  723.     open(CMD, "| some_cmd its_args > a_file");
  724.     while ($condition) {
  725.         print CMD "some output\n";
  726.         # other code deleted
  727.     } 
  728.     close CMD || warn "cmd exited $?";
  729.  
  730.     # now read the file
  731.     open(FILE,"a_file");
  732.     while (<FILE>) {
  733.  
  734.     If you have ptys, you could arrange to run the command on a pty and
  735.     avoid the deadlock problem.  See the chat2.pl package in the
  736.     distributed library for ways to do this.
  737.  
  738.     At the risk of deadlock, it is theoretically possible to use a
  739.     fork, two pipe calls, and an exec to manually set up the two-way
  740.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  741.     but this is not as portable.)  The open2 library function distributed
  742.     with the current perl release will do this for you.
  743.  
  744.     It assumes it's going to talk to something like adb, both writing to
  745.     it and reading from it.  This is presumably safe because you "know"
  746.     that commands like adb will read a line at a time and output a line at
  747.     a time.  Programs like sort that read their entire input stream first,
  748.     however, are quite apt to cause deadlock.
  749.  
  750.  
  751. 2.15) How can I change the first N letters of a string?
  752.  
  753.     Remember that the substr() function produces an lvalue, that is, it may be
  754.     assigned to.  Therefore, to change the first character to an S, you could
  755.     do this:
  756.  
  757.     substr($var,0,1) = 'S';
  758.  
  759.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  760.     you should use this instead:
  761.  
  762.     substr($var,$[,1) = 'S';
  763.  
  764.     While it would be slower, you could in this case use a substitute:
  765.  
  766.     $var =~ s/^./S/;
  767.     
  768.     But this won't work if the string is empty or its first character is a
  769.     newline, which "." will never match.  So you could use this instead:
  770.  
  771.     $var =~ s/^[^\0]?/S/;
  772.  
  773.     To do things like translation of the first part of a string, use substr,
  774.     as in:
  775.  
  776.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  777.  
  778.     If you don't know then length of what to translate, something like
  779.     this works:
  780.  
  781.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  782.     
  783.     For some things it's convenient to use the /e switch of the 
  784.     substitute operator:
  785.  
  786.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  787.  
  788.     although in this case, it runs more slowly than does the previous example.
  789.  
  790.  
  791. 2.16) How can I manipulate fixed-record-length files?
  792.  
  793.     The most efficient way is using pack and unpack.  This is faster than
  794.     using substr.  Here is a sample chunk of code to break up and put back
  795.     together again some fixed-format input lines, in this case, from ps.
  796.  
  797.     # sample input line:
  798.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  799.     $ps_t = 'A6 A4 A7 A5 A*';
  800.     open(PS, "ps|");
  801.     $_ = <PS>; print;
  802.     while (<PS>) {
  803.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  804.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  805.         print "$var: <", eval "\$$var", ">\n";
  806.         }
  807.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  808.     }
  809.  
  810.  
  811. 2.17) How can I make a file handle local to a subroutine?
  812.  
  813.     You must use the type-globbing *VAR notation.  Here is some code to
  814.     cat an include file, calling itself recursively on nested local
  815.     include files (i.e. those with #include "file", not #include <file>):
  816.  
  817.     sub cat_include {
  818.         local($name) = @_;
  819.         local(*FILE);
  820.         local($_);
  821.  
  822.         warn "<INCLUDING $name>\n";
  823.         if (!open (FILE, $name)) {
  824.         warn "can't open $name: $!\n";
  825.         return;
  826.         }
  827.         while (<FILE>) {
  828.         if (/^#\s*include "([^"]*)"/) {
  829.             &cat_include($1);
  830.         } else {
  831.             print;
  832.         }
  833.         }
  834.         close FILE;
  835.     }
  836.  
  837.  
  838. 2.18) How can I extract just the unique elements of an array?
  839.  
  840.     There are several possible ways, depending on whether the
  841.     array is ordered and you wish to preserve the ordering.
  842.  
  843.     a) If @in is sorted, and you want @out to be sorted:
  844.  
  845.     $prev = 'nonesuch';
  846.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  847.  
  848.        This is nice in that it doesn't use much extra memory, 
  849.        simulating uniq's behavior of removing only adjacent
  850.        duplicates.
  851.  
  852.     b) If you don't know whether @in is sorted:
  853.  
  854.     undef %saw;
  855.     @out = grep(!$saw{$_}++, @in);
  856.  
  857.     c) Like (b), but @in contains only small integers:
  858.  
  859.     @out = grep(!$saw[$_]++, @in);
  860.  
  861.     d) A way to do (b) without any loops or greps:
  862.  
  863.     undef %saw;
  864.     @saw{@in} = ();
  865.     @out = sort keys %saw;  # remove sort if undesired
  866.  
  867.     e) Like (d), but @in contains only small positive integers:
  868.  
  869.     undef @ary;
  870.     @ary[@in] = @in;
  871.     @out = sort @ary;
  872.  
  873.  
  874. 2.19) How can I call alarm() or usleep() from Perl?
  875.  
  876.     It's available as a built-in as of version 3.038.  If you want finer
  877.     granularity than 1 second (as usleep() provides) and have itimers and
  878.     syscall() on your system, you can use the following.  You could also
  879.     use select().
  880.  
  881.     It takes a floating-point number representing how long to delay until
  882.     you get the SIGALRM, and returns a floating- point number representing
  883.     how much time was left in the old timer, if any.  Note that the C
  884.     function uses integers, but this one doesn't mind fractional numbers.
  885.  
  886.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  887.     # tom christiansen <tchrist@convex.com>
  888.     sub alarm {
  889.     require 'syscall.ph';
  890.     require 'sys/time.ph';
  891.  
  892.     local($ticks) = @_;
  893.     local($in_timer,$out_timer);
  894.     local($isecs, $iusecs, $secs, $usecs);
  895.  
  896.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  897.  
  898.     $secs = int($ticks);
  899.     $usecs = ($ticks - $secs) * 1e6;
  900.  
  901.     $out_timer = pack($itimer_t,0,0,0,0);  
  902.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  903.  
  904.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  905.         && die "alarm: setitimer syscall failed: $!";
  906.  
  907.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  908.     return $secs + ($usecs/1e6);
  909.     }
  910.  
  911.  
  912. 2.20) How can I test whether an array contains a certain element?
  913.  
  914.     There are several ways to approach this.  If you are going to make
  915.     this query many times and the values are arbitrary strings, the
  916.     fastest way is probably to invert the original array and keep an
  917.     associative array lying about whose keys are the first array's values.
  918.  
  919.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  920.     undef %is_blue;
  921.     for (@blues) { $is_blue{$_} = 1; }
  922.  
  923.     Now you can check whether $is_blue{$some_color}.  It might have been
  924.     a good idea to keep the blues all in an assoc array in the first place.
  925.  
  926.     If the values are all small integers, you could use a simple
  927.     indexed array.  This kind of an array will take up less space:
  928.  
  929.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  930.     undef @is_tiny_prime;
  931.     for (@primes) { $is_tiny_prime[$_] = 1; }
  932.  
  933.     Now you check whether $is_tiny_prime[$some_number].
  934.  
  935.     If the values in question are integers, but instead of strings,
  936.     you can save quite a lot of space by using bit strings instead:
  937.  
  938.     @articles = ( 1..10, 150..2000, 2017 );
  939.     undef $read;
  940.     grep (vec($read,$_,1) = 1, @articles);
  941.     
  942.     Now check whether vec($read,$n,1) is true for some $n.
  943.  
  944.  
  945. 2.21) How can I do an atexit() or setjmp()/longjmp() in Perl?
  946.  
  947.     Perl's exception-handling mechanism is its eval operator.  You 
  948.     can use eval as setjmp and die as longjmp.  Here's an example
  949.     of Larry's for timed-out input, which in C is often implemented
  950.     using setjmp and longjmp:
  951.  
  952.       $SIG{ALRM} = TIMEOUT;
  953.       sub TIMEOUT { die "restart input\n" }
  954.  
  955.       do { eval { &realcode } } while $@ =~ /^restart input/;
  956.  
  957.       sub realcode {
  958.           alarm 15;
  959.           $ans = <STDIN>;
  960.           alarm 0;
  961.       }
  962.  
  963.    Here's an example of Tom's for doing atexit() handling:
  964.  
  965.     sub atexit { push(@_exit_subs, @_) }
  966.  
  967.     sub _cleanup { unlink $tmp }
  968.  
  969.     &atexit('_cleanup');
  970.  
  971.     eval <<'End_Of_Eval';  $here = __LINE__;
  972.     # as much code here as you want
  973.     End_Of_Eval
  974.  
  975.     $oops = $@;  # save error message
  976.  
  977.     # now call his stuff
  978.     for (@_exit_subs) { &$_() }
  979.  
  980.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  981.         " line " . ($1+$here)/e, die $oops);
  982.  
  983.     You can register your own routines via the &atexit function now.  You
  984.     might also want to use the &realcode method of Larry's rather than
  985.     embedding all your code in the here-is document.  Make sure to leave
  986.     via die rather than exit, or write your own &exit routine and call
  987.     that instead.   In general, it's better for nested routines to exit
  988.     via die rather than exit for just this reason.
  989.  
  990.     In Perl5, it will be easy to set this up because of the automatic
  991.     processing of per-package END functions.
  992.  
  993.     Eval is also quite useful for testing for system dependent features,
  994.     like symlinks, or using a user-input regexp that might otherwise
  995.     blowup on you.
  996.  
  997.  
  998. 2.22) Why doesn't Perl interpret my octal data octally?
  999.  
  1000.     Perl only understands octal and hex numbers as such when they occur
  1001.     as constants in your program.  If they are read in from somewhere
  1002.     and assigned, then no automatic conversion takes place.  You must
  1003.     explicitly use oct() or hex() if you want this kind of thing to happen.
  1004.     Actually, oct() knows to interpret both hex and octal numbers, while
  1005.     hex only converts hexadecimal ones.  For example:
  1006.  
  1007.     {
  1008.         print "What mode would you like? ";
  1009.         $mode = <STDIN>;
  1010.         $mode = oct($mode);
  1011.         unless ($mode) {
  1012.         print "You can't really want mode 0!\n";
  1013.         redo;
  1014.         } 
  1015.         chmod $mode, $file;
  1016.     } 
  1017.  
  1018.     Without the octal conversion, a requested mode of 755 would turn 
  1019.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  1020.  
  1021.     If you want something that handles decimal, octal and hex input, 
  1022.     you could follow the suggestion in the man page and use:
  1023.  
  1024.     $val = oct($val) if $val =~ /^0/;
  1025.  
  1026. 2.23) How do I sort an associative array by value instead of by key?
  1027.  
  1028.     You have to declare a sort subroutine to do this.  Let's assume
  1029.     you want an ASCII sort on the values of the associative array %ary.
  1030.     You could do so this way:
  1031.  
  1032.     foreach $key (sort by_value keys %ary) {
  1033.         print $key, '=', $ary{$key}, "\n";
  1034.     } 
  1035.     sub by_value { $ary{$a} cmp $ary{$b}; }
  1036.  
  1037.     If you wanted a descending numeric sort, you could do this:
  1038.  
  1039.     sub by_value { $ary{$b} <=> $ary{$a}; }
  1040.  
  1041.     You can also inline your sort function, like this, at least if 
  1042.     you have a relatively recent patchlevel of perl4:
  1043.  
  1044.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  1045.         print $key, '=', $ary{$key}, "\n";
  1046.     } 
  1047.  
  1048.     If you wanted a function that didn't have the array name hard-wired
  1049.     into it, you could so this:
  1050.  
  1051.     foreach $key (&sort_by_value(*ary)) {
  1052.         print $key, '=', $ary{$key}, "\n";
  1053.     } 
  1054.     sub sort_by_value {
  1055.         local(*x) = @_;
  1056.         sub _by_value { $x{$a} cmp $x{$b}; } 
  1057.         sort _by_value keys %x;
  1058.     } 
  1059.  
  1060.     If you want neither an alphabetic nor a numeric sort, then you'll 
  1061.     have to code in your own logic instead of relying on the built-in
  1062.     signed comparison operators "cmp" and "<=>".
  1063.  
  1064.     Note that if you're sorting on just a part of the value, such as a
  1065.     piece you might extract via split, unpack, pattern-matching, or
  1066.     substr, then rather than performing that operation inside your sort
  1067.     routine on each call to it, it is significantly more efficient to
  1068.     build a parallel array of just those portions you're sorting on, sort
  1069.     the indices of this parallel array, and then to subscript your original
  1070.     array using the newly sorted indices.  This method works on both
  1071.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  1072.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  1073.     Computable Field" for a simple example of this.
  1074.  
  1075.  
  1076. 2.24) How can I capture STDERR from an external command?
  1077.  
  1078.     There are three basic ways of running external commands:
  1079.  
  1080.     system $cmd;
  1081.     $output = `$cmd`;
  1082.     open (PIPE, "cmd |");
  1083.  
  1084.     In the first case, both STDOUT and STDERR will go the same place as
  1085.     the script's versions of these, unless redirected.  You can always put
  1086.     them where you want them and then read them back when the system
  1087.     returns.  In the second and third cases, you are reading the STDOUT
  1088.     *only* of your command.  If you would like to have merged STDOUT and
  1089.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  1090.     STDOUT:
  1091.  
  1092.     $output = `$cmd 2>&1`;
  1093.     open (PIPE, "cmd 2>&1 |");
  1094.  
  1095.     Another possibility is to run STDERR into a file and read the file 
  1096.     later, as in 
  1097.  
  1098.     $output = `$cmd 2>some_file`;
  1099.     open (PIPE, "cmd 2>some_file |");
  1100.     
  1101.     Here's a way to read from both of them and know which descriptor
  1102.     you got each line from.  The trick is to pipe only STDERR through
  1103.     sed, which then marks each of its lines, and then sends that
  1104.     back into a merged STDOUT/STDERR stream, from which your Perl program
  1105.     then reads a line at a time:
  1106.  
  1107.         open (CMD, 
  1108.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  1109.  
  1110.         while (<CMD>) {
  1111.           if (s/^STDERR://)  {
  1112.               print "line from stderr: ", $_;
  1113.           } else {
  1114.               print "line from stdout: ", $_;
  1115.           }
  1116.         }
  1117.  
  1118.     Be apprised that you *must* use Bourne shell redirection syntax
  1119.     here, not csh!  In fact, you can't even do these things with csh.
  1120.     For details on how lucky you are that perl's system() and backtick
  1121.     and pipe opens all use Bourne shell, fetch the file from convex.com
  1122.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  1123.     interface is the Bourne shell.
  1124.  
  1125.     There's an &open3 routine out there which will be merged with 
  1126.     &open2 in perl5 production.
  1127.  
  1128.  
  1129. 2.25) Why doesn't open return an error when a pipe open fails?
  1130.  
  1131.     These statements:
  1132.  
  1133.     open(TOPIPE, "|bogus_command") || die ...
  1134.     open(FROMPIPE, "bogus_command|") || die ...
  1135.  
  1136.     will not fail just for lack of the bogus_command.  They'll only
  1137.     fail if the fork to run them fails, which is seldom the problem.
  1138.  
  1139.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  1140.     exits prematurely or doesn't run.  If you are reading from the
  1141.     FROMPIPE, you need to check the close() to see what happened.
  1142.  
  1143.     If you want an answer sooner than pipe buffering might otherwise
  1144.     afford you, you can do something like this:
  1145.  
  1146.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  1147.     (kill 0, $kid) || die "bogus_command failed";
  1148.  
  1149.     This works fine if bogus_command doesn't have shell metas in it, but
  1150.     if it does, the shell may well not have exited before the kill 0.  You
  1151.     could always introduce a delay:
  1152.  
  1153.     $kid = open (PIPE, "bogus_command </dev/null |");
  1154.     sleep 1;
  1155.     (kill 0, $kid) || die "bogus_command failed";
  1156.  
  1157.     but this is sometimes undesirable, and in any event does not guarantee
  1158.     correct behavior.  But it seems slightly better than nothing.
  1159.  
  1160.     Similar tricks can be played with writable pipes if you don't wish to
  1161.     catch the SIGPIPE.
  1162.  
  1163.  
  1164. 2.26) How can I compare two date strings?
  1165.  
  1166.     If the dates are in an easily parsed, predetermined format, then you
  1167.     can break them up into their component parts and call &timelocal from
  1168.     the distributed perl library.  If the date strings are in arbitrary
  1169.     formats, however, it's probably easier to use the getdate program
  1170.     from the Cnews distribution, since it accepts a wide variety of dates.
  1171.     Note that in either case the return values you will really be
  1172.     comparing will be the total time in seconds as return by time().
  1173.    
  1174.     Here's a getdate function for perl that's not very efficient; you 
  1175.     can do better this by sending it many dates at once or modifying
  1176.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1177.  
  1178.     sub getdate {
  1179.         local($_) = shift;
  1180.  
  1181.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  1182.         # getdate has broken timezone sign reversal!
  1183.  
  1184.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1185.         chop;
  1186.         $_;
  1187.     } 
  1188.  
  1189.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1190.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1191.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1192.     mail for details.
  1193.  
  1194.     You might also consider using these: 
  1195.  
  1196.     date.pl        - print dates how you want with the sysv +FORMAT method
  1197.     date.shar      - routines to manipulate and calculate dates
  1198.     ftp-chat2.shar - updated version of ftpget. includes library and demo programs
  1199.     getdate.shar   - returns number of seconds since epoch for any given date
  1200.     ptime.shar     - print dates how you want with the sysv +FORMAT method
  1201.  
  1202.     You probably want 'getdate.shar'... these and other files can be ftp'd from
  1203.     the /pub/perl/scripts directory on coombs.anu.edu.au. See the README file in
  1204.     the /pub/perl directory for time and the European mirror site details.
  1205.  
  1206.  
  1207. 2.27) What's the fastest way to code up a given task in perl?
  1208.  
  1209.     Because Perl so lends itself to a variety of different approaches
  1210.     for any given task, a common question is which is the fastest way
  1211.     to code a given task.  Since some approaches can be dramatically
  1212.     more efficient that others, it's sometimes worth knowing which is
  1213.     best.  Unfortunately, the implementation that first comes to mind,
  1214.     perhaps as a direct translation from C or the shell, often yields
  1215.     suboptimal performance.  Not all approaches have the same results
  1216.     across different hardware and software platforms.  Furthermore,
  1217.     legibility must sometimes be sacrificed for speed.
  1218.  
  1219.     While an experienced perl programmer can sometimes eye-ball the code
  1220.     and make an educated guess regarding which way would be fastest,
  1221.     surprises can still occur.  So, in the spirit of perl programming
  1222.     being an empirical science, the best way to find out which of several
  1223.     different methods runs the fastest is simply to code them all up and
  1224.     time them. For example:
  1225.  
  1226.     $COUNT = 10_000; $| = 1;
  1227.  
  1228.     print "method 1: ";
  1229.  
  1230.         ($u, $s) = times;
  1231.         for ($i = 0; $i < $COUNT; $i++) {
  1232.         # code for method 1
  1233.         }
  1234.         ($nu, $ns) = times;
  1235.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1236.  
  1237.     print "method 2: ";
  1238.  
  1239.         ($u, $s) = times;
  1240.         for ($i = 0; $i < $COUNT; $i++) {
  1241.         # code for method 2
  1242.         }
  1243.         ($nu, $ns) = times;
  1244.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1245.  
  1246.     For more specific tips, see the section on Efficiency in the
  1247.     ``Other Oddments'' chapter at the end of the Camel Book.
  1248.  
  1249.  
  1250. 2.28) How can I know how many entries are in an associative array?
  1251.  
  1252.     While the number of elements in a @foobar array is simply @foobar when
  1253.     used in a scalar, you can't figure out how many elements are in an
  1254.     associative array in an analogous fashion.  That's because %foobar in
  1255.     a scalar context returns the ratio (as a string) of number of buckets
  1256.     filled versus the number allocated.  For example, scalar(%ENV) might
  1257.     return "20/32".  While perl could in theory keep a count, this would
  1258.     break down on associative arrays that have been bound to dbm files.
  1259.  
  1260.     However, while you can't get a count this way, one thing you *can* use
  1261.     it for is to determine whether there are any elements whatsoever in
  1262.     the array, since "if (%table)" is guaranteed to be false if nothing
  1263.     has ever been stored in it.  
  1264.  
  1265.     So you either have to keep your own count around and increments
  1266.     it every time you store a new key in the array, or else do it
  1267.     on the fly when you really care, perhaps like this:
  1268.  
  1269.     $count++ while each %ENV;
  1270.  
  1271.     This preceding method will be faster than extracting the
  1272.     keys into a temporary array to count them.
  1273.  
  1274.     As of a very recent patch, you can say
  1275.  
  1276.     $count = keys %ENV;
  1277. -- 
  1278.     Tom Christiansen      tchrist@cs.colorado.edu       
  1279.             Consultant
  1280.     Boulder Colorado  303-444-3212
  1281.